(function () {
    var that
    function Game(map) {
        this.map = map
        this.food = new Food()
        this.food.render(this.map)
        this.snack = new Snack()
        that = this
    }

    Game.prototype.start = function () {
        runSnake()
        // 控制键盘移动
        bindKey()
        this.snack.render(this.map)
    }
    function bindKey() {
        document.addEventListener('keydown', function (e) {
            switch (e.keyCode) {
                case 37:
                    this.snack.direction = 'left'
                    break
                case 38:
                    this.snack.direction = 'top'
                    break
                case 39:
                    this.snack.direction = 'right'
                    break
                case 40:
                    this.snack.direction = 'bottom'
                    break
            }
        }.bind(that), false)
    }
    function runSnake() {
            var timeId = setInterval(function () {

            var maxX = this.map.offsetWidth / this.snack.width
            var maxY = this.map.offsetHeight / this.snack.height
            var x = this.snack.body[0].x
            var y = this.snack.body[0].y
            this.snack.move(this.food, this.map),
            this.snack.render(this.map)
            if (x >= maxX || y >= maxY || x < 0 || y < 0) {
                clearInterval(timeId)
                alert('Game Over')
            }

        }.bind(that), 150)
    }
    window.Game = Game
})()

